﻿
using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;
using MCPlatform.ViewModels;
using MCPlatform.Shared.Contracts;
using MCPlatform.Shared.Components;
using MCPlatform.UI.Components;
using MCPlatform.UI.Contracts;
using MCPlatform.ViewModels.Shell;
using System.Diagnostics;
using System.Threading;
using System.Windows;
using MCPlatform.Views.Shell;

namespace MCPlatform.Components
{
    public class AppBootstrapper : BootstrapperBase
    {
        #region Fields
        private CompositionContainer _container = new CompositionContainer();

        private IWindowManager? _windowManager;

        private IEventAggregator? _eventAggregator;

        private ILogger? _logger;

        private IThemeManager? _themeManager;


        //是否已运行一个应用实例
        static bool _runone = false;
        //当前线程
        static Mutex _mutex = new Mutex(true, "MCPlatform", out _runone);

        LoadingViewModel _loadingViewModel = new LoadingViewModel();

        #endregion

        #region Ctor
        public AppBootstrapper()
        {
            Initialize();
        }
        #endregion

        #region Overrides
        protected override void Configure()
        {
           
            var aggregateCatalog = new AggregateCatalog(
                              AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>());

            var batch = new CompositionBatch();

            _container = new CompositionContainer(aggregateCatalog);

            batch.AddExportedValue(_container);

            //注入IoC
            _windowManager = new WindowManager();
            batch.AddExportedValue(_windowManager);
            _eventAggregator = new EventAggregator();
            batch.AddExportedValue(_eventAggregator);
            _logger = new NLogger();
            batch.AddExportedValue(_logger);
            _themeManager = new ThemeManager();
            batch.AddExportedValue(_themeManager);

            _container.Compose(batch);
        }

        protected override void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            base.OnUnhandledException(sender, e);
        }

        protected override object GetInstance(Type service, string key)
        {
            string contract = string.IsNullOrEmpty(key)
               ? AttributedModelServices.GetContractName(service)
               : key;

            var exports = _container.GetExportedValues<object>(contract);

            if (exports.Any())
                return exports.First();

            throw new Exception($"找不到实例 {contract}。");
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return _container.GetExportedValues<object>(AttributedModelServices.GetContractName(service));
        }

        protected override IEnumerable<Assembly> SelectAssemblies()
        {
          
            var assemblies = new List<Assembly>
            {
                Assembly.GetEntryAssembly()!,
                Assembly.GetExecutingAssembly(),
                typeof(UI.Controls.Views.Communicate.TcpClientControl).Assembly
            };

            return assemblies.Where(x => x != null)
                .Distinct();
        }

        protected override void BuildUp(object instance)
        {
            _container.SatisfyImportsOnce((ComposablePart)instance);
        }

        protected override  void OnStartup(object sender, System.Windows.StartupEventArgs e)
        {
            //进程锁，防止程序多开
            if (!_runone)
            {
                MessageBox.Show("已有程序在运行");
                Application.Current?.Shutdown();

            }
            else
            {
                _mutex.ReleaseMutex();
            }


             _windowManager?.ShowWindowAsync(_loadingViewModel);
         
            CheckActivationStatus();



        }



        private  void CheckActivationStatus()
        {
          
           
            ActivationManager activationManager = ActivationManager.GetInstance();
            //是否已激活
            int Ret = activationManager.CheckActivationStatus();
            //如果发现激活文件被删除，不可重复试用
            if (Ret == -999)
            {
                // activationManager.IsTrail = true;
            }

           

            if (!activationManager.IsActivated)
            {

                ActivateViewModel activateViewModel = new ActivateViewModel();

                activateViewModel.ActivateSuccessEvent += (() =>
                {


                    _windowManager?.ShowWindowAsync(new ShellViewModel());

                    activateViewModel.TryCloseAsync();

                   

                });

               
                 _windowManager?.ShowDialogAsync(activateViewModel);
                

            }
            else
            {
                _windowManager?.ShowWindowAsync(new ShellViewModel());

            }


            CloseLoading();
        }

        public void CloseLoading()
        {
            //Application.Current?.Dispatcher?.Invoke(() =>
            //{
            //    _loadingViewModel.Close();
            //});
            _loadingViewModel.TryCloseAsync();
        }

       
        #endregion
    }
}
